package com.laozhao.msas.util;

import java.awt.Toolkit;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class NumberField extends JTextField {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7766646453110003951L;
	private Pattern intp = Pattern.compile("[+-]?[0123456789]*[.]?");
	private Pattern dicp = Pattern
			.compile("[+-]?[0123456789]*[.][0123456789]*");

	public NumberField() {
		super();
		setDocument(new NumberDocument());
	}

	public Integer getIntValue() {
		return getDoubleValue().intValue();
	}

	public Double getDoubleValue() {
		return Double.parseDouble(getText());
	}

	@Override
	public void setText(String text) {
		if (text != null && !"".equals(text)) {
			super.setText(text);
		} else {
			super.setText("0");
		}
	}

	public void setNumber(Number num) {
		if (num != null) {
			super.setText(num.toString());
		} else {
			super.setText("0");
		}
	}

	class NumberDocument extends PlainDocument {
		/**
		 * 
		 */
		private static final long serialVersionUID = 618631385104970883L;

		public NumberDocument() {
			super();
		}

		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			try {
				String text = getText(0, getLength()) + str;
				boolean result = intp.matcher(text).matches();
				boolean result1 = dicp.matcher(text).matches();

//				System.out
//						.println("str is:" + str + "\t offs is:" + offs
//								+ "\t a is:" + a + "\t text is:" + text
//								+ "\t result is:" + result + "\t result1 is:"
//								+ result1);
				if (result || result1) {
					super.insertString(offs, str, a);
				}
			} catch (Exception e) {
				Toolkit.getDefaultToolkit().beep();
			}
		}
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		NumberField nun = new NumberField();
		frame.add(nun);
		// nun.setScale(5, 2);
		nun.setText("123456.290099");
		frame.setVisible(true);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocationRelativeTo(null);
	}

}
